package com.shanghaionstar.login.service;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.onstar.cn.api.OauthService;
import com.onstar.cn.api.UsersService;
import com.onstar.cn.api.VehicleService;
import com.onstar.cn.api.util.AuthUtils;
import com.onstar.cn.api.v3.UserService;
import com.onstar.cn.auth.AuthTokenEntity;
import com.onstar.cn.auth.AuthTokenRequestEntity;
import com.onstar.cn.auth.LoginEntity;
import com.onstar.cn.auth.userProfile.Subscriber;
import com.onstar.cn.auth.userProfile.request.UserProfileRequest;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.core.BaseService;
import com.onstar.cn.framework.network.ClientTraceInstance;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.network.http.ResponseHandler;
import com.onstar.cn.framework.network.http.Sender;
import com.onstar.cn.framework.utils.ExceptionUtil;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.PlateEngineNumEntity;
import com.onstar.cn.mag.enumtype.OSType;
import com.onstar.cn.more.response.PersonalInfoResponse;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.vehicle.response.features.ServiceFeatureCommandEntity;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.life.AlarmManagerUtil;
import com.shanghaionstar.login.HomeOrCompanyInfoIntentService;
import com.shanghaionstar.login.LoginActivity;
import com.shanghaionstar.login.SupplementPhoneActivity;
import com.shanghaionstar.login.presenter.RetryWithDelay;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.AuthorUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.utils.NetConnectUtil;

import java.text.ParseException;
import java.util.LinkedHashMap;

import rx.Observable;
import rx.functions.Func0;

/**
 * Created by 6335yz on 2016/6/27.
 */
public class LoginSerice extends BaseService {
    private Context context;

    public LoginSerice(Context context) {
        this.context = context;
    }

    private LogManager log = LogManager.getInstance();

    @Override
    public RequestEntity getRequestEntity() {
        return null;
    }

    @Override
    public Object jsonToBean(String json) {
        return null;
    }

    public Observable<AuthTokenEntity> login(final String userName, final String password) {
        return Observable.defer(new Func0<Observable<AuthTokenEntity>>() {
            @Override
            public Observable<AuthTokenEntity> call() {
                try {
                    LoginEntity loginEntity = new LoginEntity();
                    loginEntity.setName(userName);
                    loginEntity.setPassword(password);
                    return Observable.just(getAuthToken(loginEntity));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    public Observable<String> deleteToken(final boolean isRevokeIdToken) {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(deleteAuthToken(isRevokeIdToken));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    public Observable<Subscriber> loadUserProfile() {
        return Observable.defer(new Func0<Observable<Subscriber>>() {
            @Override
            public Observable<Subscriber> call() {
                try {
                    return Observable.just(getUserProfile()).retryWhen(new RetryWithDelay(2, 3000));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.POST)
    public AuthTokenEntity getAuthToken(LoginEntity loginEntity) throws OnStarException {
        long startTimeStamp = System.currentTimeMillis();
        boolean isSuccess = true;
        AuthTokenRequestEntity entity = BusinessUtil.createAuthTokenRequestEntity();
        entity.setPassword(loginEntity.getPassword());
        entity.setUserName(loginEntity.getName());
        entity.setDeviceId(new DeviceUtil(context).getDeviceID());
        OauthService oauthService = new OauthService(Constants.CURRENT_AUTH_URL);
        try {
            RequestEntity requestEntity = oauthService.autoToken(new RequestEntity(), entity.getUserName(), entity.getPassword(),
                    entity.getClientId(), entity.getDeviceId(), entity.getClientSecret(), entity.getScope());
            requestEntity = HttpInjectUtils.injectHttp(getClass(), "getAuthToken", requestEntity, LoginEntity.class);
            String response = AuthUtils.decodeJwtToJson(NetConnectUtil.getResponse(getDatas(requestEntity)));

            AuthTokenEntity responseEntity = GsonHelper.fromJson(response, AuthTokenEntity.class);
            ApplicationUtil.getInstance().updateToken(responseEntity.getTokenType(),
                    responseEntity.getAccessToken());
            saveTokenInPreference(responseEntity.getIdToken(), responseEntity.getTokenType() + " "
                    + responseEntity.getAccessToken(), true);
        } catch (HttpException e) {
            isSuccess = false;
            ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(context, e);
            if (errorInfo != null && errorInfo.getCode()!=null && "E9004".equals(errorInfo.getCode())) {
                throw new HttpException(errorInfo.getCode(), errorInfo.getMsg());
            } else if(errorInfo != null){
                throw ExceptionUtil.defaultException(new HttpException("", errorInfo.getMsg()));
            } else {
                throw ExceptionUtil.defaultException(e);
            }
        } catch (Exception e) {
            isSuccess = false;
            throw ExceptionUtil.defaultException(e);
        }finally {
            long endTimeStamp = System.currentTimeMillis();
            ReportReqParam reportReqParam = ReportReqParam.getLoginReqParm(isSuccess);
            reportReqParam.startTimestamp = startTimeStamp;
            reportReqParam.endTimestamp = endTimeStamp;
            reportReqParam.functionNameFindId = FunctionNameFindId.ManualLogin_GetToken.getStringValue();

            BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.ManualLogin_GetToken.getStringValue(),reportReqParam);
        }
        return null;
    }


    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.DELETE)
    public String deleteAuthToken(boolean isRevokeIdToken) throws OnStarException {
        AuthTokenRequestEntity entity = BusinessUtil.createAuthTokenRequestEntity();
        entity.setDeviceId(new DeviceUtil(context).getDeviceID());
        OauthService oauthService = new OauthService(Constants.CURRENT_AUTH_URL);
        String response = null;
        try {
            RequestEntity requestEntity = oauthService.deleteToken(NetConnectUtil.getAuthRequestEntity(context), String.valueOf(isRevokeIdToken));
            requestEntity = HttpInjectUtils.injectHttp(getClass(), "deleteAuthToken", requestEntity, boolean.class);
            try {
                response = NetConnectUtil.getResponse(getDatas(requestEntity));
                log.d("after delete the access token, the result is ---->>" + response);
            } catch (HttpException e) {
                ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(context, e);
                throw new HttpException(errorInfo.getCode(), errorInfo.getMsg());
            }
        } catch (Exception e) {
            throw ExceptionUtil.defaultException(e);
        }
        return response;
    }


    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public Subscriber getUserProfile() throws OnStarException {
        boolean isSuccess = true;
        long startTimeStamp = System.currentTimeMillis();
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        UserProfileRequest request = new UserProfileRequest();
        DeviceUtil deviceUtil = new DeviceUtil(context);
        request.setOsType(OSType.ANDROID.value());
        request.setVersionCode(deviceUtil.getAppVersionCode() + "");
        request.setOSVersion(DeviceUtil.getOSVersion());

        requestEntity = service.getUserInfo3Profile(requestEntity, GsonHelper.toJson(request));//getUserProfile
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getUserProfile", requestEntity);
        Subscriber subscriber=null;
        try{
            String response = NetConnectUtil.getResponse(getDatas(requestEntity));
            PreferencesUtls.getInstance(context).putString(Constants.AUTH_USER_PROFILE, response);
            PreferencesUtls.getInstance(context).putLong(Constants.AUTH_USER_PROFILE_TIME, System.currentTimeMillis());
            subscriber = GsonHelper.fromJson(response, Subscriber.class);
        }catch (OnStarException e) {
            isSuccess = false;
            throw e;
        }finally {
            long endTimeStamp = System.currentTimeMillis();
            ReportReqParam reportReqParam = ReportReqParam.getLoginReqParm(isSuccess);
            reportReqParam.startTimestamp = startTimeStamp;
            reportReqParam.endTimestamp = endTimeStamp;
            reportReqParam.functionNameFindId = FunctionNameFindId.ManualLogin_GetProfile.getStringValue();
            BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.ManualLogin_GetProfile.getStringValue(),reportReqParam);
        }

        handleSubscriber(subscriber);
        return subscriber;
    }

    /**
     * @param subscriber
     * @throws OnStarException Onstar7.1中确定是否需要补充手机号
     */
    public void handleSubscriber(Subscriber subscriber) throws OnStarException {
        if (context instanceof LoginActivity) {
            if (!subscriber.isAppFlag()) {
                // TODO: 2016/10/24 是info3.0但非app或微信注册用户跳转验证页面
                saveTokenInPreference("", "", true);
                return;
            }
            if (!CommonUtil.isNull(subscriber) && !subscriber.isEmptyPhoneNo()) {
                handleSubscriberNotFromLogin(subscriber);
                return;
            }
            if (!CommonUtil.isNull(subscriber) && subscriber.isEmptyPhoneNo()) {
                Intent it = new Intent(context, SupplementPhoneActivity.class);
                if (subscriber != null) {
                    it.putExtra("gaaPhoneNumber", subscriber.getGaaPhoneNumber() == null ? "" : subscriber.getGaaPhoneNumber());
                    OnstarApplication application = (OnstarApplication) context.getApplicationContext();
//                    application.setLoginRole(subscriber.getRole());
                }
                ((LoginActivity) context).startActivityForResult(it, LoginActivity.REQUEST_SUPPLEMENT);
            }
        } else {
            handleSubscriberNotFromLogin(subscriber);
        }
    }

    private void handleSubscriberNotFromLogin(Subscriber subscriber) throws OnStarException {
        if (!CommonUtil.isNull(subscriber)) {
            log.d("load user profile end ");
            // 更新User profile 信息
            ApplicationUtil.getInstance().updateUserProfile(subscriber);
            // 如果当前登录角色为Visitor，那么直接返回数据，不需要更新Vehicle unit feature
            if (!CommonUtil.isNull(subscriber) && !CommonUtil.isNull(subscriber.getRole())
                    && subscriber.getRole().equalsIgnoreCase(JoinMeConstants.VISITOR)) {
                onSuccess();
            } else {
                Observable.just(getVehicleFeatures(subscriber)).retryWhen(new RetryWithDelay(2, 3000));
            }
        }
    }


    public Observable<Subscriber> loadUserProfile4Cache() {
        return Observable.defer(new Func0<Observable<Subscriber>>() {
            @Override
            public Observable<Subscriber> call() {
                try {
//                    BusinessUtil.sendReportByClickType(context, FunctionNameFindId.Login_GetProfile.getStringValue());
                    return Observable.just(getUserProfile4Cache());
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public Subscriber getUserProfile4Cache() throws OnStarException {
        boolean isSuccess = true;
        long startTimeStamp = System.currentTimeMillis();
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        UserProfileRequest request = new UserProfileRequest();
        DeviceUtil deviceUtil = new DeviceUtil(context);
        request.setOsType(OSType.ANDROID.value());
        request.setVersionCode(deviceUtil.getAppVersionCode() + "");
        request.setOSVersion(DeviceUtil.getOSVersion());

        requestEntity = service.getUserInfo3Profile(requestEntity, GsonHelper.toJson(request));
//        requestEntity = service.getUserProfile(requestEntity, JsonUtils.object2Json(request));
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getUserProfile4Cache", requestEntity);
        Subscriber subscriber=null;
        try{
            String response = NetConnectUtil.getResponse(getDatas(requestEntity));
            PreferencesUtls.getInstance(context).putString(Constants.AUTH_USER_PROFILE, response);
            PreferencesUtls.getInstance(context).putLong(Constants.AUTH_USER_PROFILE_TIME, System.currentTimeMillis());
            subscriber = GsonHelper.fromJson(response, Subscriber.class);

        }catch (HttpException e) {
            isSuccess = false;
            throw e;
        }finally {
            long endTimeStamp = System.currentTimeMillis();
            ReportReqParam reportReqParam = ReportReqParam.getLoginReqParm(isSuccess);
            reportReqParam.startTimestamp = startTimeStamp;
            reportReqParam.endTimestamp = endTimeStamp;
            reportReqParam.functionNameFindId = FunctionNameFindId.Login_GetProfile.getStringValue();

            BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.Login_GetProfile.getStringValue(),reportReqParam);
        }

        if (!CommonUtil.isNull(subscriber)) {
            log.d("load user profile end ");
            // 更新User profile 信息
            ApplicationUtil.getInstance().updateUserProfile(subscriber);
            // 如果当前登录角色为Visitor，那么直接返回数据，不需要更新Vehicle unit feature
            if (!CommonUtil.isNull(subscriber) && !CommonUtil.isNull(subscriber.getRole())
                    && subscriber.getRole().equalsIgnoreCase(JoinMeConstants.VISITOR)) {
                onSuccessWithOutRefresh();
            } else {
//                BusinessUtil.sendReportByClickType(context, FunctionNameFindId.Login_GetCommand.getStringValue());
                getVehicleFeaturesForCache(subscriber);
            }
        }

//        handleSubscriberNotFromLogin(subscriber);

//        if (!CommonUtil.isNull(subscriber)) {
//            log.d("load user profile end ");
//            // 更新User profile 信息
//            ApplicationUtil.updateUserProfile(context, subscriber);
//            // 如果当前登录角色为Visitor，那么直接返回数据，不需要更新Vehicle unit feature
//            if (!CommonUtil.isNull(subscriber) && !CommonUtil.isNull(subscriber.getRole())
//                    && subscriber.getRole().equalsIgnoreCase(JoinMeConstants.VISITOR)) {
//                onSuccess();
//            }
//        }
//        boolean isOverDue = true;
//        List<CorePackage> corePackages = subscriber.getCorePackages();
//        if (corePackages != null && corePackages.size() != 0) {
//            CorePackage corePackage = corePackages.get(0);
//            String expireDate = corePackage.getExpiryDate();
//            if (!CommonUtil.isNull(expireDate)) {
//                expireDate = expireDate.replace("T", "");
//                expireDate = expireDate.replace("Z", "");
//                isOverDue = DateFormatUtil.isOverDue(expireDate);
//            }
//        }
//        if (isOverDue) {
//            if (!(!CommonUtil.isNull(subscriber) && !CommonUtil.isNull(subscriber.getRole())
//                    && subscriber.getRole().equalsIgnoreCase(JoinMeConstants.VISITOR))) {
//                getVehicleFeatures(subscriber);
//                onSuccess();
//            }
//        } else {
//            loadCacheCommands(subscriber);
//            onSuccess();
//        }
        return subscriber;
    }

    public void loadCacheCommands(Subscriber subscriber) {
        String accessToken = PreferencesUtls.getInstance(context).getString(Constants.ACCESS_TOKEN);
        String[] tokenSplit = accessToken.split("@");
        String featureJson = PreferencesUtls.getInstance(context).getString(Constants.AUTH_USER_FEATURE);
        LogManager.getInstance().d("featureJson---->" + featureJson);
        if (tokenSplit.length == 2) {
            accessToken = tokenSplit[1];
        }
        ApplicationUtil.getInstance().updateToken("", accessToken);
        ApplicationUtil.getInstance().updateUserProfile(subscriber);
        if (!CommonUtil.isNull(featureJson) && !JoinMeConstants.VISITOR.equalsIgnoreCase(subscriber.getRole())) {
            ServiceFeatureCommandEntity entity = GsonHelper.fromJson(
                    featureJson, ServiceFeatureCommandEntity.class);
            ApplicationUtil.getInstance().updateVehicleUnitFeatures(entity);
        }
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public ServiceFeatureCommandEntity getVehicleFeatures(final Subscriber subscriber) throws OnStarException {
        boolean isSuccess = true;
        long startTimeStamp = System.currentTimeMillis();
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        VehicleService service = new VehicleService(Constants.CURRENT_SERVER_URL);
        String vin = "";
        if (ApplicationUtil.getInstance().getCurrentVehicle()!=null ){
            vin = ApplicationUtil.getInstance().getCurrentVehicle().getVin();
        }
        if (subscriber != null && !CommonUtil.isNull(subscriber.getVin())) {
            vin = subscriber.getVin();
        }
        requestEntity = service.commands(requestEntity, vin);
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getVehicleFeatures", requestEntity, Subscriber.class);
        String response;
        try {
            response = NetConnectUtil.getResponse(getDatas(requestEntity));
            PreferencesUtls.getInstance(context).putString(Constants.AUTH_USER_FEATURE, response);
            ServiceFeatureCommandEntity entity = GsonHelper.fromJson(response, ServiceFeatureCommandEntity.class);
            ApplicationUtil.getInstance().updateVehicleUnitFeatures(entity);
            onSuccess();
            return entity;
        } catch (HttpException e) {
            isSuccess = false;
            throw e;
        }finally {
            long endTimeStamp = System.currentTimeMillis();
            ReportReqParam reportReqParam = ReportReqParam.getLoginReqParm(isSuccess);
            reportReqParam.startTimestamp = startTimeStamp;
            reportReqParam.endTimestamp = endTimeStamp;
            reportReqParam.functionNameFindId = FunctionNameFindId.ManualLogin_GetCommand.getStringValue();
            BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.ManualLogin_GetCommand.getStringValue(),reportReqParam);
        }
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public ServiceFeatureCommandEntity getVehicleFeaturesForCache(final Subscriber subscriber) throws OnStarException {
        boolean isSuccess = true;
        long startTimeStamp = System.currentTimeMillis();

        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        VehicleService service = new VehicleService(Constants.CURRENT_SERVER_URL);
        String vin = "";
        if (ApplicationUtil.getInstance().getCurrentVehicle()!=null ){
            vin = ApplicationUtil.getInstance().getCurrentVehicle().getVin();
        }
        if (subscriber != null && !CommonUtil.isNull(subscriber.getVin())) {
            vin = subscriber.getVin();
        }
        requestEntity = service.commands(requestEntity, vin);
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getVehicleFeaturesForCache", requestEntity, Subscriber.class);
        String response;
        try {
            response = NetConnectUtil.getResponse(getDatas(requestEntity));
            PreferencesUtls.getInstance(context).putString(Constants.AUTH_USER_FEATURE, response);
            ServiceFeatureCommandEntity entity = GsonHelper.fromJson(response, ServiceFeatureCommandEntity.class);
            ApplicationUtil.getInstance().updateVehicleUnitFeatures( entity);
            onSuccessWithOutRefresh();
            return entity;
        } catch (HttpException e) {
            isSuccess = false;
            throw e;
        }finally {
            long endTimeStamp = System.currentTimeMillis();
            ReportReqParam reportReqParam = ReportReqParam.getLoginReqParm(isSuccess);
            reportReqParam.startTimestamp = startTimeStamp;
            reportReqParam.endTimestamp = endTimeStamp;
            reportReqParam.functionNameFindId = FunctionNameFindId.Login_GetCommand.getStringValue();

            BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.Login_GetCommand.getStringValue(),reportReqParam);
        }
    }

    public void onSuccess() {
        BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.loginregister_Login.getStringValue(), ReportReqParam.getLoginReqParm(true));
        LogManager.getInstance().d("login successfully and willing to send broadcast start.....");
        ApplicationUtil.getInstance().setAutoLoging(false);
        /**
         * update the polling status with failure if exist.
         */
        AuthorUtil.getInstance().finisLogin(context);

        /**
         * launch intent service for getting company / home info
         */
        Intent homeCompanyIntent = new Intent(context, HomeOrCompanyInfoIntentService.class);
        context.startService(homeCompanyIntent);

        /**
         * 刷新登陆后页面
         */
        RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.LOGIN_SUCCESS);

        if (ApplicationUtil.getInstance().isExpiredSubscriber()) {
            RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.PACKAGE_OVERDUE);
        }
        String role = ApplicationUtil.getInstance().getLoginRole();
        if (!TextUtils.isEmpty(role) && role.equalsIgnoreCase(JoinMeConstants.OWNER)) {
            localAlarm();
        }
        ClientTraceInstance.getInstance().setIdpId(ApplicationUtil.getInstance().getIdpID());

    }

    public void onSuccessWithOutRefresh() {
        BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.loginregister_Login.getStringValue(), ReportReqParam.getLoginReqParm(true));
        LogManager.getInstance().d("login successfully and willing to send broadcast start.....");
        ApplicationUtil.getInstance().setAutoLoging(false);
        /**
         * update the polling status with failure if exist.
         */
        AuthorUtil.getInstance().finisLogin(context);

        /**
         * launch intent service for getting company / home info
         */
        Intent homeCompanyIntent = new Intent(context, HomeOrCompanyInfoIntentService.class);
        context.startService(homeCompanyIntent);

//        if (ApplicationUtil.getInstance().isExpiredSubscriber()) {
//            RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.PACKAGE_OVERDUE);
//        }
        String role = ApplicationUtil.getInstance().getLoginRole();
        if (!TextUtils.isEmpty(role) && role.equalsIgnoreCase(JoinMeConstants.OWNER)) {
            localAlarm();
        }
        ClientTraceInstance.getInstance().setIdpId(ApplicationUtil.getInstance().getIdpID());

    }

    //登陆成功后,设置本地推送
    private void localAlarm() {
        getPersonalInfo();
        getInsuranceInfo();
    }


    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public void getPersonalInfo() {
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        UserService publicService = new UserService(Constants.CURRENT_SERVER_URL);
        requestEntity = publicService.getPresonalInfomation(requestEntity);
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getPersonalInfo", requestEntity);
        Sender sender = new Sender();
        sender.send(requestEntity, new ResponseHandler() {
            @Override
            public void onSuccess(String tag, String json) {
                PersonalInfoResponse personalInfoResponse = GsonHelper.fromJson(json, PersonalInfoResponse.class);
                String licenseExpireDate = personalInfoResponse == null ? "" : personalInfoResponse.getLicenseExpireDate();
                setRenewalAlarm(context, licenseExpireDate);
            }

            private void setRenewalAlarm(Context context, String expireDate) {
                try {
                    if (!TextUtils.isEmpty(expireDate) && AlarmManagerUtil.diffTime(expireDate) > 0)
                        AlarmManagerUtil.setRenewalAlarmManager(context, expireDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String tag, HttpException e) {

            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public void getInsuranceInfo() {
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        UsersService usersService = new UsersService(Constants.CURRENT_SERVER_URL);
        requestEntity = usersService.getVehicleInfo(ApplicationUtil.getInstance().getIdpID(), ApplicationUtil.getInstance().getAccountId(), ApplicationUtil.getInstance().getVin());
        requestEntity = HttpInjectUtils.getDefaultConfig(Language.AUTO, HttpMethod.GET, HttpAccept.JSON, requestEntity);
        LinkedHashMap<String, Object> customHeads = new LinkedHashMap<String, Object>();
        customHeads.put(FinalConstants.HTTP_AUTHORIZATION, ApplicationUtil.getInstance().getToken());
        requestEntity.setCustomHeads(customHeads);
        requestEntity = HttpInjectUtils.injectHttp(getClass(), "getInsuranceInfo", requestEntity);
        Sender sender = new Sender();
        sender.send(requestEntity, new ResponseHandler() {
            @Override
            public void onSuccess(String tag, String json) {
                PlateEngineNumEntity object = GsonHelper.fromJson(json, PlateEngineNumEntity.class);
                String businessInsuranceExpireDate = object == null ? "" : object.getBusinessInsuranceExpireDate();
                String compulsoryInsuranceExpireDate = object == null ? "" : object.getCompulsoryInsuranceExpireDate();
                setInsuranceAlarm(context, true, businessInsuranceExpireDate);
                setInsuranceAlarm(context, false, compulsoryInsuranceExpireDate);
            }

            private void setInsuranceAlarm(Context context, boolean isBusiness, String expireDate) {
                try {
                    if (!TextUtils.isEmpty(expireDate) && AlarmManagerUtil.diffTime(expireDate) > 0)
                        AlarmManagerUtil.setInsuranceAlarmManager(context, isBusiness ? AlarmManagerUtil.IAlarmAction.ALARM_RECEIVER_BUSINESS_ASSURANCE_ACTION : AlarmManagerUtil.IAlarmAction.ALARM_RECEIVER_COMPULSORY_ASSURANCE_ACTION, expireDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String tag, HttpException e) {

            }
        });
    }


    /**
     * 保存TOKEN到本地Preference文件中
     *
     * @param idToken
     * @param accessToken
     */
    private void saveTokenInPreference(String idToken, String accessToken, boolean isNormal) {
        /**
         * 存放token
         */
        if (isNormal) {
            accessToken = Constants.ACCESS_TOKEN_NORMAL + "@" + accessToken;
        } else {
            accessToken = Constants.ACCESS_TOKEN_HIGH + "@" + accessToken;
        }
        PreferencesUtls.getInstance(context).putString(Constants.ID_TOKEN, idToken);
        PreferencesUtls.getInstance(context).putString(Constants.ACCESS_TOKEN, accessToken);

        /**
         * 存放token时间
         */
        PreferencesUtls.getInstance(context).putString(Constants.TIME_ID_TOKEN, System.currentTimeMillis() + "");
        PreferencesUtls.getInstance(context).putString(Constants.TIME_LOCAL_TOKEN, System.currentTimeMillis() + "");
    }
}
